package avicit.bdp.dcs.semistructure.suite;

import avicit.bdp.dcs.Constant;
import avicit.bdp.dcs.detail.dto.DataDetailDto;
import avicit.bdp.dcs.detail.dto.TableDetailDto;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.semistructure.dto.CatalogDto;
import avicit.bdp.dcs.semistructure.dto.CatalogTemplateDTO;
import avicit.bdp.dcs.semistructure.dto.FileDto;
import avicit.bdp.dcs.semistructure.dto.IotdbJsonDto;
import avicit.bdp.dcs.semistructure.dto.TemplateDTO;
import avicit.bdp.dcs.semistructure.utils.Constants;
import avicit.bdp.dcs.task.dto.TaskDTO;
import avicit.bdp.dcs.threshold.utils.TestUtils;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class DataSyncTest {
    public static final String USER_NAME = "avicit2015";
    public static final String PASS_WORD = "avicit2015";
    public static final String HTTP_OK = "200";
    public static final String URL_PREFIX = Constant.HOSTPORT;
    private String jobName = "半结构数据同步门槛用例";
    private String templateFileName;
    private String parentCatalogPath = "hdfs://192.168.0.28:8020/";
    private String catalogName;
    private String dataFileName;
    private String iotdbTimeseries = "root.1019.test";
    private String suffix = ".txt";
//    private String suffix = ".csv";
    private int skipLines = 10;
//    private String iotdbDataType = "TEXT";
    private String iotdbDataType = "DOUBLE";

    @Before
    public void setUp() throws Exception {
        // 创建模板文件
        templateFileName = "template_" + System.currentTimeMillis() + suffix;
        File file = new File(System.getProperty("user.dir") + "/" + templateFileName);
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file.getName(), true);
        fileWriter.write("name,age,work");
        fileWriter.close();
        System.out.println("模板文件创建成功！");
        // 创建数据文件
        catalogName = "testCatalog" + System.currentTimeMillis();
        dataFileName = "data_" + System.currentTimeMillis() + suffix;
        File dataFile = new File(System.getProperty("user.dir") + "/" + dataFileName);
        if(!dataFile.exists()){
            dataFile.createNewFile();
        }
        FileWriter dataFileWriter = new FileWriter(dataFile.getName(), true);
        dataFileWriter.write("name,age,work" + "\r\n");
        int num = 0;
        while (num < 1000) {
            dataFileWriter.write(num + "," + num + "," + num + "\r\n");
            num++;
        }
        dataFileWriter.close();
        System.out.println("数据文件创建成功！");
    }

    @After
    public void tearDown() throws Exception {
        // 删除模板文件
        File templateFile = new File(System.getProperty("user.dir") + "/" + templateFileName);
        templateFile.delete();
        System.out.println("删除模板文件成功！");
        // 删除数据文件
        File dataFile = new File(System.getProperty("user.dir") + "/" + dataFileName);
        dataFile.delete();
        System.out.println("删除数据文件成功！");
    }
    @Test
    public void testDataSync() throws InterruptedException {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        String templateId = "";
        String jobId = "";
        try{
            // 1：上传模板文件
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);
            FileSystemResource fileSystemResource =
                    new FileSystemResource(System.getProperty("user.dir") + "/" + templateFileName);
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
            form.add("file", fileSystemResource);
            form.add("filename",templateFileName);
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            ResponseMsg uploadResult = restTemplate.postForObject(Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/" + "upload", files, ResponseMsg.class);
            assertEquals(HTTP_OK, uploadResult.getRetCode());
            System.out.println("1：上传模板文件成功");
            List<String> columnList = (List<String>) uploadResult.getResponseBody();
            // 2：获取模板列表
            ResponseEntity<ResponseMsg> startListResult = restTemplate.getForEntity(Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/" + "getTemplateListByName",
                    ResponseMsg.class);
            ResponseMsg body = startListResult.getBody();
            List<TemplateDTO> list = (List<TemplateDTO>) body.getResponseBody();
            int startSize = list.size();
            System.out.println("模板个数为：" + startSize);
            assertEquals(HTTP_OK, startListResult.getBody().getRetCode());
            System.out.println("2：获取模板列表成功");
            // 3：创建模板
            ResponseEntity<ResponseMsg> result = restTemplate.postForEntity(Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/" + "createTemplate",
                    buildSaveTemplateParas(
                            "test",templateFileName, columnList), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("3：创建模板成功");
            // 4：获取模板列表
            ResponseEntity<ResponseMsg> endListResult = restTemplate.getForEntity(Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/" + "getTemplateListByName",
                    ResponseMsg.class);
            ResponseMsg endBody = endListResult.getBody();
            List<Map> endList = (List<Map>) endBody.getResponseBody();
            int endSize = endList.size();
            System.out.println("模板个数为：" + startSize);
            assertEquals(HTTP_OK, endListResult.getBody().getRetCode());
            assertEquals(1, endSize - startSize);
            System.out.println("4：获取模板列表成功");
            endList.removeAll(list);
            // 获取模板id
            for (Map templateDto: endList) {
                templateId = (String) templateDto.get("id");
            }
            // 5：创建目录
            ResponseEntity<ResponseMsg> catalogResult = restTemplate.postForEntity(URL_PREFIX +
                            "/api/bdp/dcs/file/FileRest/saveCatalog",
                    buildSaveCatalogParas(catalogName, parentCatalogPath), ResponseMsg.class);
            assertEquals("200", catalogResult.getBody().getRetCode());
            System.out.println("5：创建目录成功");
            // 6：目录关联模板
            ResponseEntity<ResponseMsg> saveCatalogTemplateResult = restTemplate.postForEntity(URL_PREFIX +
                            "/api/bdp/dcs/file/FileRest/saveCatalogTemplate",
                    buildSaveCatalogTemplateParas(parentCatalogPath + catalogName, templateId), ResponseMsg.class);
            assertEquals("200", saveCatalogTemplateResult.getBody().getRetCode());
            System.out.println("6：目录关联模板成功");
            // 7：上传文件
            FileSystemResource dataFileSystemResource =
                    new FileSystemResource(System.getProperty("user.dir") + "/" + dataFileName);
            MultiValueMap<String, Object> dataFileForm = new LinkedMultiValueMap<>();
            dataFileForm.add("file", dataFileSystemResource);
            dataFileForm.add("filename", dataFileName);
            dataFileForm.add("hdfsPath", parentCatalogPath + catalogName);
            HttpEntity<MultiValueMap<String, Object>> dataFiles = new HttpEntity<>(dataFileForm, headers);
            ResponseMsg uploadDataFileResult = restTemplate.postForObject(URL_PREFIX + "/api/bdp/dcs/file/FileRest" +
                            "/upload", dataFiles,
                    ResponseMsg.class);
            assertEquals(HTTP_OK, uploadDataFileResult.getRetCode());
            System.out.println("7：上传文件成功");
            // 8：保存数据源
            ResponseEntity<ResponseMsg> saveDataSourceResult = restTemplate.postForEntity(URL_PREFIX
                            + "/api/bdp/dcs/job/JobRest/saveDataSource", TestUtils.buildSaveDataSourceParas(3,
                    jobName, TestUtils.HDFS_DATASOURCE_ID, TestUtils.IOTDB_DATASOURCE_ID, 1),
                    ResponseMsg.class);
            assertEquals("200", saveDataSourceResult.getBody().getRetCode());
            System.out.println("8：保存数据源成功");
            // 获取创建的JobId
            ResponseMsg responseMsg = saveDataSourceResult.getBody();
            Map<String, String> jobMap = (Map<String, String>)responseMsg.getResponseBody();
            jobId = jobMap.get("jobId");
            // 9：保存文件和时间序列映射关系
            result = restTemplate.postForEntity(URL_PREFIX + "/api/bdp/dcs/job/JobRest/saveTableMapping",
                    buildSaveTblMapping(3, jobId, parentCatalogPath + catalogName, iotdbTimeseries), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("9：保存文件和时间序列映射关系成功");
            // 10：获取任务信息
            result = restTemplate.getForEntity(Constant.HOSTPORT + "/api/bdp/dcs/task/TaskRest/getTaskById?jobId=" +
                            jobId + "&srcTableName=" + parentCatalogPath + catalogName,
                    ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("10：获取任务信息成功");
            Map taskMap = (Map) result.getBody().getResponseBody();
            // 获取任务id
            String taskId = (String) taskMap.get("id");
            // 11：修改任务配置
            result = restTemplate.postForEntity(URL_PREFIX + "/api/bdp/dcs/task/TaskRest/updateTask",
                    buildUpdateTaskParam(taskId), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("11：修改任务配置成功");
            // 12：任务配置检查
            result = restTemplate.postForEntity(URL_PREFIX + "/api/bdp/dcs/job/JobRest/checkTaskConfig",
                    TestUtils.buildCheckTaskConfig(jobId), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("12：任务配置检查成功");
            // 13：预检查
            result = restTemplate.postForEntity(URL_PREFIX + "/api/bdp/dcs/precheck/PrecheckRest" +
                            "/executePrecheck",
                    TestUtils.buildPreChecks(jobId), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("13：预检查成功");
            // 14：更新Job状态
            result = restTemplate.postForEntity(URL_PREFIX + "/api/bdp/dcs/job/JobRest/updateJobStatus",
                    TestUtils.buildUpdateJobStatus(jobId), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("14：更新Job状态成功");
            // 15：启动任务
            result = restTemplate.postForEntity(URL_PREFIX + "/api/bdp/dcs/job/JobRest/startJobByIds",
                    TestUtils.buildStartJob(jobId), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("15：启动任务成功");
            // 获取Job列表
            // 等待DS启动任务成功
            Thread.sleep(50 * 1000);
            result = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs/job/JobRest/getJobList" +
                            "?jobStatus&sort&name=" + jobName + "&jobType=3&currentPage=1&pageSize=10",
                    HttpMethod.GET, TestUtils.buildGetHttpEntity(), ResponseMsg.class);
            ResponseMsg jobListBody = result.getBody();
            LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>)jobListBody.getResponseBody();
            List<Object> finalBody = (List<Object>) map.get("result");
            for (Object obj : finalBody) {
                LinkedHashMap<String, String> jobObj = (LinkedHashMap<String, String>)obj;
                JobDTO jobInfo = JSON.parseObject(JSON.toJSONString(jobObj), JobDTO.class);
                if (jobInfo.getId().equals(jobId)) {
                    System.out.println("半结构数据同步门槛用例任务状态:" + jobInfo.getJobStatus());
                    // 16：判断任务是否同步完成;
                    assertEquals(7 == jobInfo.getJobStatus(), true);
                    System.out.println("16：判断任务是否同步完成成功");
//                    // 17：判断同步数据大小;（备注：源表中只有一行数据，大小固定）
//                    assertEquals(jobInfo.getReadSucceedBytes() == 8670, true);
//                    System.out.println("17：判断同步数据大小成功");
                    break;
                }
            }

            // 18：查看日志信息
            result = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs/log/LogRest/getLogByTaskId" +
                    "?taskInstanceId=&skipLineNum=0" +
                    "&limit=100&jobId="+jobId, HttpMethod.GET, TestUtils.buildGetHttpEntity(), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("18：查看日志信息成功");
            // 19：查看详情，表结构迁移；
            result = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs/detail/TaskTableDetailRest" +
                            "/getTaskTableDetailList" +
                            "?currentPage=1&pageSize=20&srcTableName=&jobId="+jobId, HttpMethod.GET,
                    TestUtils.buildGetHttpEntity(), ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("19：查看详情，表结构迁移成功");
            body = result.getBody();
            map = (LinkedHashMap<String, Object>)body.getResponseBody();
            finalBody = (List<Object>) map.get("result");
            for (Object obj : finalBody) {
                LinkedHashMap<String, String> jobObj = (LinkedHashMap<String, String>)obj;
                TableDetailDto tableDetailDto = JSON.parseObject(JSON.toJSONString(jobObj), TableDetailDto.class);
                // 判断任务task是否同步遷移完成;
                assertEquals(7 == tableDetailDto.getTaskStatus(), true);
                System.out.println("19.1：判断任务task是否同步遷移完成成功");
            }
            // 20：查看详情，数据迁移；
            result = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs/detail/TaskDataDetailRest" +
                            "/getTaskDataDetailList" +
                            "?currentPage=1&pageSize=20&srcTableName=&jobId="+jobId, HttpMethod.GET,
                    TestUtils.buildGetHttpEntity(),
                    ResponseMsg.class);
            assertEquals("200", result.getBody().getRetCode());
            System.out.println("20：查看详情，数据迁移成功");
            body = result.getBody();
            map = (LinkedHashMap<String, Object>)body.getResponseBody();
            finalBody = (List<Object>) map.get("result");
            for (Object obj : finalBody) {
                LinkedHashMap<String, String> jobObj = (LinkedHashMap<String, String>)obj;
                DataDetailDto dataDetailDto = JSON.parseObject(JSON.toJSONString(jobObj), DataDetailDto.class);
                // 判断任务是否task是否同步遷移完成;
                assertEquals(7 == dataDetailDto.getTaskStatus(), true);
                System.out.println("20.1：判断任务是否task是否同步遷移完成成功");
                // 判斷完成總數是否為1000條；
//                assertEquals(dataDetailDto.getEstimateTotal() == 2, true);
                // 判斷已完成總數是否為1000條；
                assertEquals(dataDetailDto.getCompletedTotal() == 1001 - skipLines, true);
                System.out.println("20.2：判斷已完成總數是否為1000條成功");
            }
        } finally {
            // 21：删除文件
            ResponseEntity<ResponseMsg> deleteFileResult = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs/file/FileRest/deleteFileByPaths",
                    HttpMethod.DELETE, buildDeleteFileParas(parentCatalogPath + catalogName + "/" + dataFileName),
                    ResponseMsg.class);
            assertEquals(HTTP_OK, deleteFileResult.getBody().getRetCode());
            System.out.println("21：删除文件成功");
            // 22：删除job
            ResponseEntity<ResponseMsg> deleteJobResult = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs" +
                            "/job/JobRest" +
                            "/deleteJobByIds",
                    HttpMethod.DELETE,
                    TestUtils.buildDeleteJob(jobId),
                    ResponseMsg.class);
            assertEquals("200", deleteJobResult.getBody().getRetCode());
            System.out.println("22：删除job成功");
            // 23：目录解除关联模板
            ResponseEntity<ResponseMsg> cancelCatalogTemplateResult = restTemplate.postForEntity(URL_PREFIX +
                            "/api/bdp/dcs/file/FileRest/cancelCatalogTemplate",
                    buildCancelCatalogTemplateParas(parentCatalogPath + catalogName),
                    ResponseMsg.class);
            assertEquals("200", cancelCatalogTemplateResult.getBody().getRetCode());
            System.out.println("23：目录解除关联模板成功");
            // 24：删除模板
            ResponseEntity<ResponseMsg> deleteResult = restTemplate.exchange(Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/" + "deleteTemplateByIds",
                    HttpMethod.DELETE, buildDeleteTemplateParas(templateId), ResponseMsg.class);
            assertEquals(HTTP_OK, deleteResult.getBody().getRetCode());
            System.out.println("24：删除模板成功");
            // 25：删除目录
            ResponseEntity<ResponseMsg> deleteCatalogResult = restTemplate.exchange(URL_PREFIX + "/api/bdp/dcs/file" +
                            "/FileRest/deleteCatalogByPath",
                    HttpMethod.DELETE, buildDeleteCatalogParas(parentCatalogPath + catalogName),
                    ResponseMsg.class);
            assertEquals(HTTP_OK, deleteCatalogResult.getBody().getRetCode());
            System.out.println("25：删除目录成功");
        }
    }

    private HttpEntity<String> buildUpdateTaskParam(String taskId) {
        TaskDTO taskDTO = new TaskDTO();
        taskDTO.setId(taskId);
        IotdbJsonDto iotdbJsonDto = new IotdbJsonDto();
        iotdbJsonDto.setSkipFileHeader(1);
        iotdbJsonDto.setSkipLine(skipLines);
        taskDTO.setIotdbJsonDto(iotdbJsonDto);
        taskDTO.setModifyColumn(0);
        taskDTO.setMappingColumn("[{\"desensitizationPolicyId\":\"\",\"desensitizationRuleId\":\"\",\"dstColumnName\":\"name\",\"dstColumnType\":\"TEXT\",\"srcColumnName\":\"name\",\"srcColumnType\":\"TEXT\"},{\"desensitizationPolicyId\":\"\",\"desensitizationRuleId\":\"\",\"dstColumnName\":\"age\",\"dstColumnType\":\"TEXT\",\"srcColumnName\":\"age\",\"srcColumnType\":\"TEXT\"},{\"desensitizationPolicyId\":\"\",\"desensitizationRuleId\":\"\",\"dstColumnName\":\"work\",\"dstColumnType\":\"TEXT\",\"srcColumnName\":\"work\",\"srcColumnType\":\"TEXT\"}]");
        String param = JSONObject.toJSONString(taskDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((USER_NAME + ":" + PASS_WORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 保存表映射关系参数
     */
    public static HttpEntity<String> buildSaveTblMapping(int jobType, String jobId,
                                                         String srcTblName, String dstTbleName) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        jobDTO.setTransferType("1,2");
        jobDTO.setProcessMode(1);
        jobDTO.setSelectedFile(srcTblName);
        jobDTO.setExtraParams(dstTbleName);

        // 数据同步
        if (jobType == 1) {
            jobDTO.setJobType(1);
        }
        // 数据同步-增量同步
        else if (jobType == 2) {
            jobDTO.setSyncInterval(1800);
            jobDTO.setTableInit(1);
            jobDTO.setJobType(2);
        } else if (jobType == 3) {
            jobDTO.setSyncInterval(60);
            jobDTO.setTableInit(1);
            jobDTO.setJobType(3);
        }

        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((USER_NAME + ":" + PASS_WORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    private HttpEntity<String> buildDeleteCatalogParas(String catalogPath) {
        CatalogDto catalogDto = new CatalogDto();
        catalogDto.setCatalogPath(catalogPath);
        String param = JSONObject.toJSONString(catalogDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private HttpEntity<String> buildDeleteFileParas(String filePath) {
        FileDto fileDto = new FileDto();
        fileDto.setFilePath(filePath);
        String param = JSONObject.toJSONString(fileDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private HttpEntity<String> buildCancelCatalogTemplateParas(String catalogPath) {
        CatalogTemplateDTO catalogTemplateDTO = new CatalogTemplateDTO();
        catalogTemplateDTO.setCatalogPath(catalogPath);
        String param = JSONObject.toJSONString(catalogTemplateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private HttpEntity<String> buildSaveCatalogTemplateParas(String catalogPath, String templateId) {
        CatalogTemplateDTO catalogTemplateDTO = new CatalogTemplateDTO();
        catalogTemplateDTO.setTemplateId(templateId);
        catalogTemplateDTO.setCatalogPath(catalogPath);
        String param = JSONObject.toJSONString(catalogTemplateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private HttpEntity<String> buildSaveCatalogParas(String catalogName, String parentCatalogPath) {
        CatalogDto catalogDto = new CatalogDto();
        catalogDto.setParentCatalogPath(parentCatalogPath);
        catalogDto.setCatalogName(catalogName);
        String param = JSONObject.toJSONString(catalogDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private HttpEntity<String> buildDeleteTemplateParas(String templateId) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setId(templateId);
        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }
    private HttpEntity<String> buildSaveTemplateParas(String remark, String templateName, List<String> columnList) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setRemark(remark);
        JSONArray jsonArray = new JSONArray();
        for (String column: columnList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", column);
            jsonObject.put("type", iotdbDataType);
            jsonArray.add(jsonObject);
        }
//        templateDTO.setColumnRule("[{\"name\":\"name\",\"type\":\"TEXT\"},{\"name\":\"age\",\"type\":\"TEXT\"},{\"name\":\"work\",\"type\":\"TEXT\"}]");
        templateDTO.setColumnRule(jsonArray.toJSONString());
        templateDTO.setTemplateName(templateName);
        // 文件类型，excel：1，csv：2，text：3
        templateDTO.setFileType(3);
        if (".csv".equals(suffix)) {
            templateDTO.setFileType(2);
        }
        templateDTO.setFileSeparator(",");
        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }
}
